import cquery from '@dfeidao/atom-nodejs/db/complex-query';
import log from '@dfeidao/atom-nodejs/logger/log';
import { IncomingHttpHeaders } from 'http';
import { file_url, productid, systemid } from '../atom/config';

interface Message {
	filter: {
		teacher_no: string;
	};
	page_no: number;
}
interface D {
	student_no: string;
	student_name: string;
	headimg: string;
	productid: string;
	phone: string;
	uri: {};
}
interface IWebResult {
	data: {
		d: Array<{
			key: D;
		}>,
		total_size: number
	};
	cookie?: {
		[name: string]: string;
	} | null;
	content_type?: string;
	headers?: {
		[key: string]: string[];
	};
	attachment?: string;
	redirect?: string;
	status_code?: number;
}

export default async function atom(message: Message, action_id: string, session_id: string, headers: IncomingHttpHeaders): Promise<IWebResult> {
	log('Service begin path:app-student-list/s001,action_id:' + action_id);
	const cq = cquery(action_id, session_id, systemid);
	const a = await cq
		.outer_left_join('student', 'class_student', ['student_no', 'student_no'])
		.outer_left_join('class_student', 'class_teacher', ['class_id', 'class_id'])
		.outer_left_join('student', 'parent_information', ['student_no', 'student_no'])
		.where_eq('class_teacher', 'teacher_no', message.filter.teacher_no)
		.where_eq('parent_information', 'urgent_contact', '1')
		.add_fun('student', '_id', 'total_size', 'count')
		.exec() as Array<{ total_size: number }>;
	const total_size = a[0].total_size;
	const c = await cq
		.add_field('student', 'productid', 'productid')
		.add_field('student', 'student_no', 'student_no')
		.add_field('student', 'student_name', 'student_name')
		.add_field('student', 'headimg', 'headimg')
		.add_field('parent_information', 'phone', 'phone')
		.outer_left_join('student', 'class_student', ['student_no', 'student_no'])
		.outer_left_join('class_student', 'class_teacher', ['class_id', 'class_id'])
		.outer_left_join('student', 'parent_information', ['student_no', 'student_no'])
		.where_eq('class_teacher', 'teacher_no', message.filter.teacher_no)
		.where_eq('parent_information', 'urgent_contact', '1')
		.page(20, message.page_no)
		.exec();
	const d = c.map((i: D) => {
		i.uri = i.headimg ? { uri: file_url + '/getfile?productid=' + productid + '&id=' + i.headimg } : '';
		return { key: i };
	});
	log('Service end path:app-student-list/s001,action_id:' + action_id);
	return { data: { d, total_size } } as IWebResult;
}
